"""
xapper buildxaps admin command definition.
"""

from __future__ import print_function
from __future__ import unicode_literals

import os, sys
from django.core.management.base import BaseCommand
from optparse import make_option
from xapper.appdef import SilverlightApp

class Command(BaseCommand):
    help = "Builds static .xap files for the specified applications, or the entire site if no " \
        "apps are specified."
    option_list = BaseCommand.option_list + (
        make_option("--outdir", "-o", action="store", dest="outdir", help="Output directory"),
    )
    args = "[appname ...]"

    requires_model_validation = False

    def handle(self, *app_labels, **options):
        from xapper.conf import settings

        xap_dir = options["outdir"]
        if xap_dir:
          if not os.path.isdir(xap_dir):
            print("The specified output directory does not exist or is not a directory: {0}"
                  .format(xap_dir), file=sys.stderr)
            sys.exit(-1)
        else:
          xap_dir = settings.XAPPER_STATIC_XAP_DIR
          if not xap_dir or not os.path.isabs(xap_dir) or not os.path.isdir(xap_dir):
            print("XAPPER_STATIC_XAP_DIR is not set correctly.  It must either be set to the "
                  "absoulte path of a directory or the --outdir option must be specified in order "
                  "to use this command.", file=sys.stderr)
            sys.exit(-1)

        if not app_labels:
          app_labels = settings.INSTALLED_APPS

        silverlight_apps = set()

        for app_label in app_labels:
          if app_label in settings.INSTALLED_APPS:
            try:
              xaps_module = getattr(__import__(".".join((app_label, "xaps")), {}, {}, []), "xaps")
            except ImportError as e:
              if unicode(e) != "No module named xaps":
                raise
            else:
              silverlight_apps.update(a for a in xaps_module.__dict__.itervalues()
                                      if isinstance(a, SilverlightApp))
          else: # app_label isn't a Django app
            try:
              silverlight_app = SilverlightApp.get_app(app_label)
            except ValueError:
              print("Unknown app name '{0}'.  This is neither a Django app nor a Silverlight app.",
                    file=sys.stderr)
              sys.exit(-1)
            else:
              silverlight_apps.add(silverlight_app)

        for silverlight_app in silverlight_apps:
          filename = os.path.join(xap_dir, silverlight_app.name + ".xap")
          with open(filename, "wb") as xap_file:
            silverlight_app.build_xap(xap_file)
